package com.sise.aio和bio和nio.bio;

import java.io.*;
import java.net.Socket;

/**
 * @author idea
 * @data 2019/1/20
 */
public class ServerHandler implements Runnable {

    private Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        int count = 0;
        try {
            //客户端到服务端 输入流
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //服务端到客户端 输出流
            out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            String expression;
            while (true) {
                if ((expression = in.readLine()) == null) {
                    break;
                } else {
                    System.out.println("client传输数据为：" + expression);
                    if (count == 3) {
                        out.print("exit");
                        out.flush();
                    } else {
                        out.print("this is server!");
                        out.flush();
                    }
                }
                count++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                out = null;
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }
        }
    }
}
